<template>
  <div class="commentWapper">
    <div class="title">评 论</div>
    <div class="popup" v-show="isReply">
      <span class="text">回复 @{{ params.name }}</span>
      <i class="el-icon-close concel" @click="isReply = false"></i>
    </div>
    <el-form v-model="form">
      <el-input
        v-model="form.content"
        placeholder="说点什么吧..."
        type="textarea"
        :rows="2"
        class="input"
        resize="none"
        ref="popup"
      ></el-input>
      <div class="control">
        <el-upload
          :action="$axios.defaults.baseURL + '/upload'"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :show-file-list="true"
          name="files"
          :on-success="handleSuccess"
          ref="img"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
        <div class="publish" @click="submitComment">发表</div>
      </div>
    </el-form>

    <div class="mianWapper">
      <!-- 遍历每一项主评论 -->
      <div
        class="mainItem"
        v-for="(mianComment, index) in commentList"
        :key="index"
      >
        <div class="info">
          <img
            :src="$axios.defaults.baseURL + mianComment.account.defaultAvatar"
            alt=""
            class="avatar"
          />
          <div class="username">{{ mianComment.account.nickname }}</div>
          <div class="date">{{ mianComment.created_at }}</div>
        </div>

        <!-- 主评论内容样式 -->
        <div class="content">
          <Child v-if="mianComment.parent" :data="mianComment.parent" />
          <div class="showReact">
            <div class="text">{{ mianComment.content }}</div>
            <img
              :src="$axios.defaults.baseURL + mian.url"
              alt=""
              class="contentImg"
              v-for="(mian, index) in mianComment.pics"
              :key="index"
            />
            <div
              class="react"
              @click="
                reply({
                  id: mianComment.id,
                  name: mianComment.account.nickname,
                })
              "
            >
              回复
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页器 -->
    <el-pagination
      :page-size="pageSize"
      :current-page="1"
      layout="total,prev, pager, next"
      :total="total"
      @current-change="indexChange"
    >
    </el-pagination>
  </div>
</template>

<script>
import Child from "@/components/post/child";
import moment from "moment";
import { EventBus } from "@/plugins/bus";

export default {
  components: {
    Child,
  },
  data() {
    return {
      commentList: [],
      form: {
        content: "",
        post: this.$route.query.id,
        pics: [],
      },
      isShow: false,
      dialogImageUrl: "",
      dialogVisible: false,

      // 分页器数据
      pageSize: 5,
      pageIndex: 0,
      total: 0,
      // 是否回复评论
      isReply: false,
      params: {},
    };
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传图片成功，回调参数
    handleSuccess(response, file, fileList) {
      this.form.pics.push(response[0]);
    },
    // 点击回复
    reply(params) {
      EventBus.$emit("handleEvent", params);
    },

    // 提交评论&&回复评论
    submitComment() {
      // 判断是否登录
      if (this.$store.state.user.userInfo.token) {
        if (this.isReply) {
          this.$axios({
            headers: {
              Authorization: "Bearer " + this.$store.state.user.userInfo.token,
              "Content-Type": "application/json",
            },
            url: "/comments",
            method: "post",
            data: {
              pics: this.form.pics,
              content: this.form.content,
              follow: this.params.id,
              post: this.form.post,
            },
          }).then((res) => {
            this.loadPage();
            this.isReply = false;
            this.form.content = "";
            this.form.pics = [];
            this.$res.img.clearFiles();
          });
        } else {
          this.$axios({
            headers: {
              Authorization: "Bearer " + this.$store.state.user.userInfo.token,
              "Content-Type": "application/json",
            },
            url: "/comments",
            method: "post",
            data: this.form,
          }).then((res) => {
            if (res.data.message == "提交成功") {
              this.$message.success(res.data.message);
              this.loadPage();
              this.form.content = "";
              this.form.pics = [];
              this.$refs.img.clearFiles();
            }
          });
        }
      } else {
        this.$router.push({
          path: "/user/login",
          query: {
            url: this.$route.fullPath,
          },
        });
      }
    },
    //分页器改变触发函数
    indexChange(newIndex) {
      this.pageIndex = newIndex;
      this.loadPage();
    },
    // 获取评论列表
    loadPage() {
      this.$axios({
        url: "/posts/comments",
        params: {
          post: this.$route.query.id,
          _limit: this.pageSize,
          _start: this.pageIndex,
        },
      }).then((res) => {
        this.total = res.data.total;
        this.commentList = res.data.data.map((item) => {
          return {
            ...item,
            created_at: moment(item.created_at).format("YYYY-MM-DD hh:mm"),
          };
        });
      });
    },
  },
  mounted() {
    // 获取文章数据
    this.loadPage();
    // 监听事件总线
    EventBus.$on("handleEvent", (params) => {
      this.params = params;
      this.isReply = true;
      this.$refs.popup.focus();
    });
  },
};
</script>

<style lang="less" scoped>
.title {
  font-size: 18px;
  margin: 10px 0;
  font-weight: none;
}
.input {
  height: 40px;
  margin: 10px 0;
}
.control {
  margin: 20px 0;
  display: flex;
  justify-content: space-between;
  .publish {
    padding: 10px 18px;
    height: 16px;
    line-height: 16px;
    background: #409eff;
    border-radius: 8px;
    color: #fff;
    cursor: pointer;
  }
}
.mianWapper {
  border: 1px solid #ddd;
  margin-bottom: 20px;
  .mainItem {
    border-bottom: 1px dashed #ddd;
    padding: 10px 20px;
    position: relative;

    .info {
      display: flex;
      align-items: center;
      padding-bottom: 5px;
      .avatar {
        width: 20px;
        height: 20px;
        object-fit: cover;
        border-radius: 50%;
      }
      .username {
        font-size: 14px;
        color: #666;
        padding-left: 8px;
      }
      .date {
        font-size: 12px;
        color: #9999a5;
        padding-left: 8px;
      }
    }

    .content {
      padding: 8px 4px;
      margin-bottom: 10px;
      .showReact {
        &:hover {
          .react {
            opacity: 1;
          }
        }
      }
      .text {
        padding-top: 8px;
      }
      .contentImg {
        width: 80px;
        height: 80px;
        object-fit: cover;
        padding: 8px;
        margin-top: 8px;
        border: 1px dashed #ddd;
      }
      .react {
        position: absolute;
        right: 20px;
        bottom: 8px;
        color: #1e50a2;
        font-size: 14px;
        cursor: pointer;
        opacity: 0;
      }
    }
  }
}

.popup {
  float: left;
  font-size: 12px;
  color: #909399;
  padding: 5px 15px;
  background: #f4f4f5;
  border: 1px solid #e0e0e3;
  border-radius: 5px;
  text-align: center;
  display: flex;
  align-items: center;
  .concel {
    padding: 3px;
    margin-left: 3px;
    &:hover {
      background: #909399;
      color: #edf8ef;
      border-radius: 50%;
    }
  }
}
</style>